<?
require_once("includes/db.php"); 
require_once("includes/utils.php"); 

//
//  Outputs a string representation of the database settings.
//
//  The string is in the format:
//      
//      12123123451234567890123456
//      OKdayhh:mmMessageOfTheDay *&ABDCEFGHIJKLM... etc.
//
//  where:
//      'day' is the name of the weekday in 3 letters (e.g. 'Mon')
//      'hh:mm' is the current server time in 24 hour clock 
//      'MessageOfTheDay' is an arbitrary 16-character string
//      '*' is the appliances (0=hot water only, 1=hot water and central heating)
//      '&' is the advance status (0=normal, 1=plus one hour, 2=advance)
//      'A', 'B', etc are binary representations of windows - grouped by day, with 3 windows per day and 2 events per day, 42 chars in total.
//      The binary representations are e.g. 101 for "10:00", 1 for "00:00", 236 for "23:50" (note we add 1 so that we don't send null chars).
//
//  If there is an error then it will write out "ERR " followed by a message.
//

$db = new DB;

$resultset = $db->query ("  SELECT 
                                message_of_the_day,
                                appliances,
                                advance_status,
   		                        last_queried,
        		                last_updated_on_server,
                 	            last_updated_on_device
                            FROM
                                heating");

if (! $resultset  ||  1 != mysql_num_rows ($resultset))
{
    ?>ERR heating <?=$db->getLastError()?><?
    return;
}




// Success!
$row = mysql_fetch_array($resultset);

$days = array();

$messageOfTheDay = $row["message_of_the_day"];
$appliances = $row["appliances"];
$advanceStatus = $row["advance_status"];
$lastQueried = $row["last_queried"];
$lastUpdatedOnServer = $row["last_updated_on_server"];
$lastUpdatedOnDevice = $row["last_updated_on_device"];


$resultset = $db->query ("  SELECT
                                day,
                                window1_start,
                                window1_end,
                                window2_start,
                                window2_end,
                                window3_start,
                                window3_end
                            FROM
                                windows
                            ORDER BY
                                day ASC");


if (! $resultset  ||  7 != mysql_num_rows ($resultset))
{
    ?>ERR windows <?=$db->getLastError()?><?
    return;
}

// Success!
$days = array();

while ($row = mysql_fetch_array($resultset))
{
    $day = $row["day"];
        
    $days[$day] = array("window1_start" => $row["window1_start"],
                        "window1_end"   => $row["window1_end"],
                        "window2_start" => $row["window2_start"],
                        "window2_end"   => $row["window2_end"],
                        "window3_start" => $row["window3_start"],
                        "window3_end"   => $row["window3_end"]);
}                        
                           
//
//  END OF INITIAL DB QUERIES
// 



$data = $_GET['DATA'];
$myFile = fopen("log.txt", 'a') or die ("Can't open log file");
fputs($myFile, date("Y-m-d H:i:s") . " Request with ?" . $queryString . "\n");
fclose($myFile);


date_default_timezone_set("Europe/London");
$sDay = date("D");
$sTime = date("H:i");



// Validation and saving
if (strlen($data) > 0)
{
    //
    // Should be in the format:
    //
    //  <isStateChangedLocally>_<lastSyncSendTime>_<lastSyncSuccessTime>_<appliances>_<advanceStatus>
    //
    $parts = explode("_", $data);
    if (sizeof($parts) >= 5)
    {
        if ("Y" == $parts[0])  // state is changed locally
        {
            $appliances = $parts[3];
            $advanceStatus = $parts[4];
            
            if (! preg_match("/^[01]$/", $appliances))
            {
                ?>ERR param appliances: <?=$appliances?><?
                return;
            }
            if (! preg_match("/^[012]$/", $advanceStatus))
            {
                ?>ERR param advanceStatus: <?=$advanceStatus?><?
                return;
            }
            
            
            // Save
            $resultset = $db->query ("UPDATE heating SET 
                              appliances         = " . makeSafeForDB($appliances) . ",
                              advance_status     = " . makeSafeForDB($advanceStatus));
            
            // TODO - check for success
        }        
    }
}


$windowsString = "";

for ($day=0; $day < 7; $day++)
{
    for ($window=0; $window < 3; $window++)
    {
        // Add binary representation of our tiny int (add 1 to each value so C++ doesn't have problems with NULL/0s)   
        $windowsString = $windowsString . chr(1 + ($days[$day]["window" . ($window + 1) . "_start"]));
        $windowsString = $windowsString . chr(1 + ($days[$day]["window" . ($window + 1) . "_end"]));
    }
}

$messageOfTheDay = substr($messageOfTheDay, 0, 16);

while (strlen($messageOfTheDay) < 16)
{
    $messageOfTheDay = $messageOfTheDay . " ";
}   

//$windowsString = "";
// dayhh:mmMessageOfTheDay ABCCCDDDEEEFFFGGGHHHIIIJJJKKKLLLMMM etc.
?>OK<?=$sDay?><?=$sTime?><?= $messageOfTheDay ?><?=$appliances?><?=$advanceStatus?><?=$windowsString?>